<template>
  <div class="dashboard-container">
    <!-- 顶部概览卡片 -->
    <div class="overview-card">
      <div class="overview-header">
        <h1>能力诊断报告</h1>
        <div class="exam-type" v-if="currentReport.data?.meta">
          {{ useuserStore.resData }}分析报告
        </div>
      </div>

      <div class="probability-badge">
        <span class="probability-value">{{
          useuserStore.resData.result[2]["content"][""] || "--"
        }}</span>
        <span class="probability-label">通过概率</span>
      </div>

      <div class="level-indicator">
        <div class="level-progress">
          <div
            class="level-fill"
            :style="{ width: currentLevelPercentage + '%' }"
          ></div>
        </div>
        <div class="level-labels">
          <span>初级</span>
          <span>中级</span>
          <span>高级</span>
          <span>专业</span>
        </div>
        <div class="current-level">
          当前水平:
          {{
            currentReport.data?.growth_roadmap?.current_status?.position || "--"
          }}
        </div>
      </div>
    </div>

    <!-- 报告选择标签页 -->
    <div class="report-tabs">
      <button
        v-for="(report, index) in reports"
        :key="index"
        :class="['tab', { active: activeReportIndex === index }]"
        @click="activeReportIndex = index"
      >
        报告 {{ index + 1 }}
      </button>
    </div>

    <!-- 主要内容区域 -->
    <div class="report-content">
      <!-- 左侧文本分析 -->
      <div class="text-analysis">
        <div class="analysis-card">
          <h3 class="card-title">优势分析</h3>
          <ul class="strength-list">
            <li
              v-for="(item, index) in strengths"
              :key="index"
              class="strength-item"
            >
              <div class="strength-icon">💪</div>
              <div>
                <div class="strength-text">{{ item.text_segment }}</div>
                <div class="strength-detail">
                  <span class="pill">{{ item.characteristic }}</span>
                  <span class="position">({{ item.position }})</span>
                </div>
              </div>
            </li>
          </ul>
        </div>

        <div class="analysis-card">
          <h3 class="card-title">待改进点</h3>
          <ul class="weakness-list">
            <li
              v-for="(item, index) in weaknesses"
              :key="index"
              class="weakness-item"
            >
              <div class="weakness-icon">⚠️</div>
              <div>
                <div class="weakness-problem">{{ item.problem }}</div>
                <div class="weakness-suggestion">
                  <span class="pill">{{ item.improvement_suggestion }}</span>
                  <span class="position">({{ item.position }})</span>
                </div>
              </div>
            </li>
          </ul>
        </div>

        <div class="analysis-card expert-comment">
          <h3 class="card-title">专家建议</h3>
          <div class="comment-content">
            {{ currentReport.data?.expert_comment || "暂无专家建议" }}
          </div>
          <div class="resources" v-if="recommendedResources.length">
            <span>推荐资源:</span>
            <span
              v-for="(resource, index) in recommendedResources"
              :key="index"
              class="resource-tag"
            >
              {{ resource }}
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧图表展示 -->
      <div class="chart-section">
        <!-- 雷达图 -->
        <div class="chart-container">
          <h3>多维能力评估</h3>
          <div ref="radarChart" style="width: 100%; height: 400px"></div>
        </div>

        <!-- 柱状图和折线图 -->
        <div class="chart-group">
          <div class="chart-container">
            <h3>能力分布</h3>
            <div ref="barChart" style="width: 100%; height: 300px"></div>
          </div>
          <div class="chart-container">
            <h3>成长预测</h3>
            <div ref="lineChart" style="width: 100%; height: 300px"></div>
          </div>
        </div>

        <!-- 饼图和热力图 -->
        <div class="chart-group">
          <div class="chart-container">
            <h3>知识掌握度</h3>
            <div ref="pieChart" style="width: 100%; height: 300px"></div>
          </div>
          <div class="chart-container">
            <h3>技能热力图</h3>
            <div ref="heatmapChart" style="width: 100%; height: 300px"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { onMounted, ref, watch, computed } from "vue";
import userStore from "../store/userStore";

export default {
  props: {
    reports: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  setup(props) {
    const activeReportIndex = ref(0);
    const radarChart = ref(null);
    const barChart = ref(null);
    const lineChart = ref(null);
    const pieChart = ref(null);
    const heatmapChart = ref(null);

    const useuserStore = userStore();

    // 计算当前报告 - 添加安全访问
    const currentReport = computed(() => {
      if (props.reports.length > 0 && props.reports[activeReportIndex.value]) {
        return props.reports[activeReportIndex.value].content || {};
      }
      return {};
    });

    // 计算当前水平百分比 - 添加安全访问
    const currentLevelPercentage = computed(() => {
      const position =
        currentReport.value.data?.growth_roadmap?.current_status?.position ||
        "";
      if (position.includes("初级")) return 25;
      if (position.includes("中级")) return 50;
      if (position.includes("高级")) return 75;
      if (position.includes("专业")) return 90;
      return 50;
    });

    // 提取优势点
    const strengths = computed(() => {
      return (
        currentReport.value.data?.diagnostic_report?.micro_analysis?.filter(
          (item) => item.analysis_type === "优势"
        ) || []
      );
    });

    // 提取待改进点
    const weaknesses = computed(() => {
      const micro =
        currentReport.value.data?.diagnostic_report?.micro_analysis?.filter(
          (item) => item.analysis_type === "缺陷"
        ) || [];

      const capability =
        currentReport.value.data?.capability_assessment?.flatMap(
          (assessment) => assessment.weaknesses || []
        ) || [];

      return [...micro, ...capability];
    });

    // 提取推荐资源
    const recommendedResources = computed(() => {
      const resources = new Set();

      // 从成长路线图中提取
      currentReport.value.data?.growth_roadmap?.stage_plan?.forEach((plan) => {
        plan.key_tasks?.forEach((task) => {
          task.resources?.forEach((resource) => resources.add(resource));
        });
      });

      // 从知识重建中提取
      currentReport.value.data?.knowledge_reconstruction?.missing_knowledge?.forEach(
        (item) => {
          item.remedy_resources?.forEach((resource) => resources.add(resource));
        }
      );

      return Array.from(resources);
    });

    // 初始化图表
    const initCharts = () => {
      // 销毁已有图表实例
      [radarChart, barChart, lineChart, pieChart, heatmapChart].forEach(
        (chartRef) => {
          if (chartRef.value && chartRef.value.chartInstance) {
            chartRef.value.chartInstance.dispose();
          }
        }
      );

      // 雷达图配置 - 添加安全访问
      const radarData =
        currentReport.value.data?.data_visualization?.radar_chart;
      if (radarData && radarChart.value) {
        const radarInstance = echarts.init(radarChart.value);
        radarChart.value.chartInstance = radarInstance;

        const option = {
          tooltip: { trigger: "item" },
          radar: {
            indicator: radarData.dimensions.map((name) => ({ name, max: 100 })),
          },
          series: [
            {
              type: "radar",
              data: [
                {
                  value: radarData.scores,
                  name: "能力评估",
                  areaStyle: { color: "rgba(58, 134, 255, 0.4)" },
                  lineStyle: { color: "#3a86ff" },
                },
              ],
            },
          ],
        };
        radarInstance.setOption(option);
      }

      // 柱状图配置 - 添加安全访问
      const barData = currentReport.value.data?.data_visualization?.bar_chart;
      if (barData && barChart.value) {
        const barInstance = echarts.init(barChart.value);
        barChart.value.chartInstance = barInstance;

        const option = {
          tooltip: { trigger: "axis" },
          xAxis: {
            type: "category",
            data: barData.categories,
          },
          yAxis: { type: "value" },
          series: [
            {
              type: "bar",
              data: barData.values,
              itemStyle: { color: "#8338ec" },
            },
          ],
        };
        barInstance.setOption(option);
      }

      // 折线图配置 - 添加安全访问
      const lineData = currentReport.value.data?.data_visualization?.line_chart;
      if (lineData && lineChart.value) {
        const lineInstance = echarts.init(lineChart.value);
        lineChart.value.chartInstance = lineInstance;

        const option = {
          tooltip: { trigger: "axis" },
          xAxis: {
            type: "category",
            data: lineData.x_values,
          },
          yAxis: { type: "value", min: 60, max: 100 },
          series: [
            {
              type: "line",
              data: lineData.y_values,
              smooth: true,
              lineStyle: { color: "#06d6a0", width: 3 },
              itemStyle: { color: "#06d6a0" },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "rgba(6, 214, 160, 0.4)" },
                  { offset: 1, color: "rgba(6, 214, 160, 0.1)" },
                ]),
              },
            },
          ],
        };
        lineInstance.setOption(option);
      }

      // 饼图配置 - 添加安全访问
      const pieData = currentReport.value.data?.data_visualization?.pie_chart;
      if (pieData && pieChart.value) {
        const pieInstance = echarts.init(pieChart.value);
        pieChart.value.chartInstance = pieInstance;

        const option = {
          tooltip: { trigger: "item" },
          legend: {
            orient: "vertical",
            right: 10,
            top: "center",
          },
          series: [
            {
              type: "pie",
              radius: ["40%", "70%"],
              data: pieData.labels.map((label, index) => ({
                value: pieData.slices[index],
                name: label,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
        pieInstance.setOption(option);
      }

      // 热力图配置 - 添加安全访问
      const heatmapData = currentReport.value.data?.data_visualization?.heatmap;
      if (heatmapData && heatmapChart.value) {
        const heatmapInstance = echarts.init(heatmapChart.value);
        heatmapChart.value.chartInstance = heatmapInstance;

        const option = {
          tooltip: { position: "top" },
          grid: {
            top: "15%",
            left: "10%",
            right: "5%",
            bottom: "15%",
          },
          xAxis: {
            type: "category",
            data: heatmapData.x_labels,
          },
          yAxis: {
            type: "category",
            data: heatmapData.y_labels,
          },
          visualMap: {
            min: 0,
            max: 1,
            calculable: true,
            orient: "horizontal",
            left: "center",
            bottom: "5%",
            inRange: {
              color: [
                "#f0f9e8",
                "#ccebc5",
                "#a8ddb5",
                "#7bccc4",
                "#43a2ca",
                "#0868ac",
              ],
            },
          },
          series: [
            {
              name: "掌握度",
              type: "heatmap",
              data: heatmapData.data.flatMap((row, yIndex) =>
                row.map((value, xIndex) => [xIndex, yIndex, value])
              ),
              label: {
                show: true,
                formatter: (param) => param.value[2].toFixed(1),
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
        heatmapInstance.setOption(option);
      }
    };

    // 监听报告变化
    watch(activeReportIndex, () => {
      initCharts();
    });

    // 监听报告数据变化
    watch(
      () => props.reports,
      () => {
        initCharts();
      },
      { deep: true }
    );

    // 组件挂载时初始化图表
    onMounted(() => {
      // 延迟初始化确保DOM加载完成
      setTimeout(initCharts, 300);

      // 响应窗口调整
      window.addEventListener("resize", () => {
        [radarChart, barChart, lineChart, pieChart, heatmapChart].forEach(
          (chartRef) => {
            if (chartRef.value?.chartInstance) {
              chartRef.value.chartInstance.resize();
            }
          }
        );
      });
    });

    return {
      activeReportIndex,
      currentReport,
      currentLevelPercentage,
      strengths,
      weaknesses,
      recommendedResources,
      radarChart,
      barChart,
      lineChart,
      pieChart,
      heatmapChart,
    };
  },
};
</script>

<style scoped>
.dashboard-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
}

/* 顶部概览卡片样式 */
.overview-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 16px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  border: 1px solid rgba(58, 134, 255, 0.15);
  position: relative;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.overview-header h1 {
  font-size: 2rem;
  margin: 0;
  background: linear-gradient(90deg, #3a86ff, #8338ec);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.exam-type {
  background-color: #eef7ff;
  color: #3a86ff;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 500;
}

.probability-badge {
  position: absolute;
  top: 25px;
  right: 25px;
  background: rgba(6, 214, 160, 0.2);
  color: #047857;
  padding: 10px 20px;
  border-radius: 50px;
  font-weight: 600;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.probability-value {
  font-size: 2.5rem;
  line-height: 1;
}

.probability-label {
  font-size: 0.9rem;
}

.level-indicator {
  margin-top: 30px;
}

.level-progress {
  height: 12px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
}

.level-fill {
  height: 100%;
  background: linear-gradient(90deg, #3a86ff, #4361ee);
  border-radius: 10px;
  transition: width 0.5s ease;
}

.level-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 0.8rem;
  color: #666;
}

.current-level {
  margin-top: 15px;
  font-weight: 500;
  color: #3a86ff;
}

/* 报告标签页样式 */
.report-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
}

.tab {
  flex: 1;
  padding: 12px 0;
  background: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.tab:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.tab.active {
  background: linear-gradient(90deg, #3a86ff, #8338ec);
  color: white;
}

/* 报告内容区域 */
.report-content {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 25px;
}

.text-analysis {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.analysis-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-title {
  font-size: 1.3rem;
  margin-bottom: 15px;
  color: #8338ec;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f2f5;
}

.strength-list,
.weakness-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.strength-item,
.weakness-item {
  display: flex;
  gap: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #f0f2f5;
}

.strength-item:last-child,
.weakness-item:last-child {
  border-bottom: none;
}

.strength-icon,
.weakness-icon {
  font-size: 1.5rem;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.strength-icon {
  background-color: rgba(6, 214, 160, 0.15);
  color: #047857;
}

.weakness-icon {
  background-color: rgba(255, 99, 132, 0.15);
  color: #b91c1c;
}

.strength-text,
.weakness-problem {
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.4;
}

.strength-detail,
.weakness-suggestion {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.pill {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.strength-detail .pill {
  background-color: rgba(6, 214, 160, 0.15);
  color: #047857;
}

.weakness-suggestion .pill {
  background-color: rgba(255, 99, 132, 0.15);
  color: #b91c1c;
}

.position {
  font-size: 0.8rem;
  color: #666;
}

.expert-comment {
  background: linear-gradient(135deg, #f8f9fa 0%, #eef7ff 100%);
  border: 1px solid rgba(58, 134, 255, 0.1);
}

.comment-content {
  font-style: italic;
  padding: 15px;
  border-left: 4px solid #3a86ff;
  background: #f8f9fa;
  border-radius: 0 8px 8px 0;
  margin: 15px 0;
  line-height: 1.6;
}

.resources {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  font-size: 0.9rem;
  margin-top: 15px;
}

.resource-tag {
  background-color: #eef7ff;
  color: #3a86ff;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.85rem;
}

/* 图表区域样式 */
.chart-section {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.chart-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.chart-container h3 {
  font-size: 1.2rem;
  margin-bottom: 15px;
  color: #4361ee;
  display: flex;
  align-items: center;
}

.chart-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px;
}

@media (max-width: 992px) {
  .report-content {
    grid-template-columns: 1fr;
  }

  .chart-group {
    grid-template-columns: 1fr;
  }
}
</style>
